﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using Microsoft.Practices.Unity;
using ORM.Business.Configuration;
using ORM.Business.Models.Entities;
using ORM.Common;
using ORM.Common.Logging;
using ORM.Configuration;
using ORM.Framework.Security;
using ORM.Framework;
using ORM.Framework.ModelBinders;
using ORM.Models;

namespace ORM
{
    // Note: For instructions on enabling IIS6 or IIS7 classic mode, 
    // visit http://go.microsoft.com/?LinkId=9394801

    public class MvcApplication : System.Web.HttpApplication
    {
        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            filters.Add(new HandleErrorAttribute());
        }

        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
            //hungnm 
            //routes.MapRoute(
            //    "Default", // Route name
            //    "{controller}/{action}/{id}", // URL with parameters
            //    new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
            //);
            routes.MapRoute(
                "Default", // Route name
                "{controller}/{action}/{id}", // URL with parameters
                new { controller = "Home", action = "index", id = UrlParameter.Optional } // Parameter defaults
            );

        }
        public static void RegisterDependencyInjection()
        {
            // Setup the dependency container
            IUnityContainer container = new UnityContainer()
                .AddNewExtension<BusinessUnityExtension>()
                .AddNewExtension<WebUnityExtension>();

            // This container will be used throughout the application lifetime
            IoC.UnityContainer = container;

            // And set as MVC dependency resolver
            DependencyResolver.SetResolver(new UnityDependencyResolver(container));
        }


        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            RegisterGlobalFilters(GlobalFilters.Filters);
            RegisterRoutes(RouteTable.Routes);
            RegisterDependencyInjection();
            ModelBinders.Binders.DefaultBinder = new TrimModelBinder();
            Database.SetInitializer<OrmEntities>(null);
        }

        protected void Application_End(object sender, EventArgs e)
        {
            Logger.Info("Application shuts down!");
        }

        protected void Session_Start(object sender, EventArgs e)
        {
            PageViewManager.IncreaseVisitorNumber();
        }

        protected void Session_End(object sender, EventArgs e)
        {
            PageViewManager.DecreaseVisitorNumber();
        }

        protected void Application_Error(object sender, EventArgs e)
        {
            Exception ex = Server.GetLastError();
            if (!(ex is HttpException))
                Logger.Error(ex);
        }

        protected void Application_PostAuthenticateRequest(object sender, EventArgs e)
        {
            if (HttpContext.Current.User.Identity.IsAuthenticated)
            {
                // Try replacing the default Principal by PermissionPrincipal
                var principal = SecurityCacheManager.GetPrincipal(User.Identity.Name);
                if (principal != null)
                {
                    HttpContext.Current.User = principal;
                }
                else // If for any reason, the user is accidentally logged in, cancel the request
                {
                    FormsAuthentication.SignOut();
                    Response.Redirect("~");
                }
            }
        }
    }
}